function AllReadyList() {
    console.log("11");
    // Ext.getCmp("viewPort").items.items[0].insert(24, {
    //     itemId: "demb",
    //     text: "保存调整时间",
    //     width: this.itemWidth,
    //     iconCls: `iconfont iconsave`,
    // }); //指定位置插入按钮
    setTimeout(function () {
        const mList = Ext.getCmp('KcBillheadList');
        const mList1 = Ext.getCmp('KcBillbodyList');

        const toolbar = Ext.getCmp("ext-comp-1036")

        toolbar.insert(23, {
            itemId: "demb-t",
            text: "验收确认时间",
            width: this.itemWidth,
            iconCls: "iconfont iconsave" //按钮形状
        });

        toolbar.insert(24, {
            itemId: "demb",
            text: "安调确认时间",
            width: this.itemWidth,
            iconCls: "iconfont iconsave" //按钮形状
        });
        toolbar.get('demb').on('click', function () {
            try {
                createWindow(OkBtn1)?.show()
            } catch (error) {
                Ext.Msg.alert("提示", "修改安调时间出现错误请联系服务器客服");
            }
        })
        toolbar.get('demb-t').on('click', function () {
            // const PhId = selected1[0].data.PhId

            try {
                createWindow(OkBtn2)?.show()
            } catch (error) {
                Ext.Msg.alert("提示", "修改验收时间出现错误请联系服务器客服");
            }
        })
        toolbar.insert(25, {
            itemId: "Evaluation_1",
            text: "供应商评价(安装调试)",
            width: this.itemWidth,
            iconCls: "iconfont iconsave" //按钮形状
        });
        toolbar.get('Evaluation_1').on('click', function () {
            var selectedheadrow = mList.getSelectionModel().getSelection();
            if (selectedheadrow.length == 0) {
                Ext.Msg.alert("提示", "请选择要评价的行");
            } else {
                var supplyid = selectedheadrow[0].data.PhidCompno;
                var phid = selectedheadrow[0].data.PhId;
                var initialScore = 80;
                var finalScore = initialScore;
                var sumcount = 0;
                execServer("select_is_evaluation_1", { phid: phid }, (res) => {
                    if (res.count == 0) return;
                    const _data = JSON.parse(res.data)[0].extendObjects;
                    if (_data.user_issue1 !== null && _data.user_issue1 !== undefined && _data.user_issue1 !== "") {
                        Ext.Msg.alert("提示", "供应商评价(安装调试)已经完成，请勿重复评价");
                        return;
                    } else {
                        execServer("select_issue", { supply: supplyid }, (res) => {
                            if (res.count == 0) return;
                            const _data = JSON.parse(res.data)[0].extendObjects;
                            sumcount = _data.sumcount ? parseInt(_data.sumcount) : 0;     // 多少个问题
                            execServer("u_jfzl_fwxy", {}, (res) => {
                                if (res.count == 0) return;
                                const _data = JSON.parse(res.data)[0].extendObjects;
                                var u1 = parseInt(_data.c_name);    // 每个扣多少
                                if (sumcount > 0) {
                                    var deduction = Math.floor(sumcount * u1);
                                    finalScore = Math.max(0, initialScore - deduction); // 确保不低于0分
                                }
                                console.log(`问题数: ${sumcount}个`);
                                console.log(`扣分规则: 每一个问题扣${u1}分`);
                                console.log(`最终得分: ${finalScore}分`);
                            });
                        });
                        Evaluation_1(finalScore, sumcount, phid)
                    }
                });
            }
        });
        toolbar.insert(26, {
            itemId: "Evaluation_2",
            text: "供应商评价(验收确认)",
            width: this.itemWidth,
            iconCls: "iconfont iconsave" //按钮形状
        });
        toolbar.get('Evaluation_2').on('click', function () {
            var selectedheadrow = mList.getSelectionModel().getSelection();
            if (selectedheadrow.length == 0) {
                Ext.Msg.alert("提示", "请选择要评价的行");
            } else {
                var supplyid = selectedheadrow[0].data.PhidCompno;
                var phid = selectedheadrow[0].data.PhId;
                var initialScore = 80;
                var finalScore = initialScore;
                var sumcount = 0;
                execServer("select_is_evaluation_2", { phid: phid }, (res) => {
                    if (res.count == 0) return;
                    const _data = JSON.parse(res.data)[0].extendObjects;
                    if (_data.user_issue2 !== null && _data.user_issue2 !== undefined && _data.user_issue2 !== "") {
                        Ext.Msg.alert("提示", "供应商评价(验收确认)已经完成，请勿重复评价");
                        return; // Exit the function to prevent further evaluation
                    } else {
                        var user_issue1 = parseInt(_data.user_issue1);
                        execServer("select_issue", { supply: supplyid }, (res) => {
                            if (res.count == 0) return;
                            const _data = JSON.parse(res.data)[0].extendObjects;
                            sumcount = _data.sumcount ? parseInt(_data.sumcount) : 0;    // 多少个问题
                            execServer("u_jfzl_fwxy", {}, (res) => {
                                if (res.count == 0) return;
                                const _data = JSON.parse(res.data)[0].extendObjects;
                                var u1 = parseInt(_data.c_name);    // 每个扣多少
                                if (sumcount > 0) {
                                    var deduction = Math.floor((sumcount - user_issue1) * u1);
                                    finalScore = Math.max(0, initialScore - deduction); // 确保不低于0分
                                }
                                console.log(`问题数: ${sumcount - user_issue1}个`);
                                console.log(`扣分规则: 每一个问题扣${u1}分`);
                                console.log(`最终得分: ${finalScore}分`);
                            });
                        });
                        Evaluation_2(finalScore, sumcount - user_issue1, phid)
                    }
                });
            }
        })
    }, 200);
    function Evaluation_1(finalScore, count, phid) {
        const fields = [
            { name: 'u_type' },
            { name: 'u_score' },
            { name: 'u_desc' },
            { name: 'u_finalscore' }
        ];
        var store = Ext.create('Ext.data.Store', {
            autoDestroy: true,
            proxy: {
                type: 'memory'
            },
            data: [],
            sorters: [{
                property: 'start',
                direction: 'ASC'
            }],
            fields: fields,
        });

        const column = [
            {
                text: '序号',
                width: 60,
                align: 'center',
                renderer: function (value, metaData, record, rowIndex) {
                    metaData.style = "text-align:center;display:flex;align-items:center;justify-content:center;height:180px";
                    return rowIndex + 1;
                },
                sortable: false,
                menuDisabled: true
            },
            {
                text: '二级分类',
                dataIndex: 'u_type',
                width: 80,
                align: 'center',
                sortable: false,
                renderer: function (value, meta) {
                    meta.style = "text-align:center;display:flex;align-items:center;justify-content:center;height:180px";
                    return value;
                },
                menuDisabled: true
            },
            {
                text: '分值',
                dataIndex: 'u_score',
                width: 40,
                align: 'center',
                sortable: false,
                renderer: function (value, meta) {
                    meta.style = "text-align:center;display:flex;align-items:center;justify-content:center;height:180px";
                    return value;
                },
                menuDisabled: true
            },
            {
                text: '标准调整',
                dataIndex: 'u_desc',
                width: 750,
                align: 'center',
                sortable: false,
                renderer: function (val, meta) {
                    meta.style = "white-space:pre-wrap;word-wrap:break-word;padding:5px;text-align:left;height:180px";
                    return val;
                },
                cellWrap: true,
                menuDisabled: true
            },
            {
                text: '得分',
                dataIndex: 'u_finalscore',
                width: 40,
                align: 'center',
                renderer: function (value, meta) {
                    meta.style = "text-align:center;display:flex;align-items:center;justify-content:center;height:180px";
                    return value;
                },
                editor: {
                    xtype: 'textfield',
                    allowBlank: false,
                    minValue: 0,      // 最小值0分
                    maxValue: 100,    // 最大值100分
                    validator: function (value) {
                        value = parseInt(value);
                        if (isNaN(value)) return "必须输入数字";
                        if (value < 0) return "分数不能小于0";
                        if (value > 100) return "分数不能超过100";
                        return true;
                    },
                    listeners: {
                        blur: function (field) {
                            let val = parseInt(field.getValue());
                            if (val > 100) field.setValue(100);
                            if (val < 0) field.setValue(0);
                        }
                    }
                }
            }
        ];
        const rowHeight = 250;
        const gridHeight = rowHeight + 30;
        const windowHeight = gridHeight + 100;

        var pgrid = new Ext.grid.GridPanel({
            height: gridHeight,
            width: 1000,
            autoScroll: false,
            cls: 'vertical-center-grid',
            store: store,
            columns: column,
            viewConfig: {
                preserveScrollOnRefresh: true,
                getRowClass: function () {
                    return 'fixed-height-row';
                }
            },
            plugins: [
                Ext.create('Ext.grid.plugin.CellEditing', {
                    clicksToEdit: 1,
                    autoCancel: false
                })
            ]
        });

        var pwin = new Ext.Window({
            title: '供应商评价',
            layout: 'fit',
            width: 1000,
            height: windowHeight,
            closable: false,
            closeAction: 'hide',
            items: [pgrid],
            header: {
                titleAlign: 'center'
            },
            buttons: [{
                text: '确定',
                handler: function () {
                    var newData = store.data.items;
                    debugger;
                    if (newData.length > 0) {
                        console.log("=======>>>>" + newData[0].data.u_finalscore);
                        console.log("=======>>>>" + newData[1].data.u_finalscore);
                        execServer('update_evaluation_1', { score1: newData[0].data.u_finalscore, score2: newData[1].data.u_finalscore, count: count, phid: phid }, function (res) {
                            if (res.status == "success") {
                                console.log("=======>>>>安装调试得分更新成功");
                            } else {
                                console.log("=======>>>>安装调试得分更新失败");
                            }
                        })
                    }
                    this.up("window").close();
                }
            }, {
                text: '返回',
                handler: function () {
                    this.up("window").close();
                }
            }],
        });
        Ext.util.CSS.createStyleSheet(`
        .vertical-center-grid .x-grid-cell-inner {
            height: 130px !important;
            padding: 0 !important;
        }
        .vertical-center-grid .x-grid-row {
            height: 130px !important;
        }
    `);

        const data = [{
            'u_type': '交付质量',
            'u_score': '100',
            'u_desc': `1、交付产品未出现质量问题，且配合海信完成业主特定需求。100分。
2、交付产品未出现质量问题。80分。
3、交付产品出现质量问题，未造成影响，60分。
4、交付产品出现质量问题，对我司项目造成一定影响，例施工进度、客户满意度（未发函、罚款）造成实施影响，30分。
5、交付产品出现质量问题，对我司项目造成严重影响，例客户投诉函件、罚款单、批次质量问题、安全问题等，0分。`,
            'u_finalscore': finalScore
        },
        {
            'u_type': '服务响应',
            'u_score': '100',
            'u_desc': ``,
            'u_finalscore': finalScore
        }];
        pgrid.store.loadData(data);
        pwin.show();
    }
    function Evaluation_2(finalScore, count, phid) {
        const fields = [
            { name: 'u_type' },
            { name: 'u_score' },
            { name: 'u_desc' },
            { name: 'u_finalscore' }
        ];
        var store = Ext.create('Ext.data.Store', {
            autoDestroy: true,
            proxy: {
                type: 'memory'
            },
            data: [],
            sorters: [{
                property: 'start',
                direction: 'ASC'
            }],
            fields: fields,
        });

        const column = [
            {
                text: '序号',
                width: 60,
                align: 'center',
                renderer: function (value, metaData, record, rowIndex) {
                    metaData.style = "text-align:center;display:flex;align-items:center;justify-content:center;height:180px";
                    return rowIndex + 1;
                },
                sortable: false,
                menuDisabled: true
            },
            {
                text: '二级分类',
                dataIndex: 'u_type',
                width: 80,
                align: 'center',
                sortable: false,
                renderer: function (value, meta) {
                    meta.style = "text-align:center;display:flex;align-items:center;justify-content:center;height:180px";
                    return value;
                },
                menuDisabled: true
            },
            {
                text: '分值',
                dataIndex: 'u_score',
                width: 40,
                align: 'center',
                sortable: false,
                renderer: function (value, meta) {
                    meta.style = "text-align:center;display:flex;align-items:center;justify-content:center;height:180px";
                    return value;
                },
                menuDisabled: true
            },
            {
                text: '标准调整',
                dataIndex: 'u_desc',
                width: 750,
                align: 'center',
                sortable: false,
                renderer: function (val, meta) {
                    meta.style = "white-space:pre-wrap;word-wrap:break-word;padding:5px;text-align:left;height:180px";
                    return val;
                },
                cellWrap: true,
                menuDisabled: true
            },
            {
                text: '得分',
                dataIndex: 'u_finalscore',
                width: 40,
                align: 'center',
                renderer: function (value, meta) {
                    meta.style = "text-align:center;display:flex;align-items:center;justify-content:center;height:180px";
                    return value;
                },
                editor: {
                    xtype: 'textfield',
                    allowBlank: false,
                    minValue: 0,      // 最小值0分
                    maxValue: 100,    // 最大值100分
                    validator: function (value) {
                        value = parseInt(value);
                        if (isNaN(value)) return "必须输入数字";
                        if (value < 0) return "分数不能小于0";
                        if (value > 100) return "分数不能超过100";
                        return true;
                    },
                    listeners: {
                        blur: function (field) {
                            let val = parseInt(field.getValue());
                            if (val > 100) field.setValue(100);
                            if (val < 0) field.setValue(0);
                        }
                    }
                }
            }
        ];
        const rowHeight = 250;
        const gridHeight = rowHeight + 30;
        const windowHeight = gridHeight + 100;

        var pgrid = new Ext.grid.GridPanel({
            height: gridHeight,
            width: 1000,
            autoScroll: false,
            cls: 'vertical-center-grid',
            store: store,
            columns: column,
            viewConfig: {
                preserveScrollOnRefresh: true,
                getRowClass: function () {
                    return 'fixed-height-row';
                }
            },
            plugins: [
                Ext.create('Ext.grid.plugin.CellEditing', {
                    clicksToEdit: 1,
                    autoCancel: false
                })
            ]
        });

        var pwin = new Ext.Window({
            title: '供应商评价',
            layout: 'fit',
            width: 1000,
            height: windowHeight,
            closable: false,
            closeAction: 'hide',
            items: [pgrid],
            header: {
                titleAlign: 'center'
            },
            buttons: [{
                text: '确定',
                handler: function () {
                    var newData = store.data.items;
                    debugger;
                    if (newData.length > 0) {
                        console.log("=======>>>>" + newData[0].data.u_finalscore);
                        console.log("=======>>>>" + newData[1].data.u_finalscore);
                        execServer('update_evaluation_2', { score1: newData[0].data.u_finalscore, score2: newData[1].data.u_finalscore, count: count, phid: phid }, function (res) {
                            if (res.status == "success") {
                                console.log("=======>>>>验收确认得分更新成功");
                            } else {
                                console.log("=======>>>>验收确认得分更新失败");
                            }
                        })
                    }
                    this.up("window").close();
                }
            }, {
                text: '返回',
                handler: function () {
                    this.up("window").close();
                }
            }],
        });
        Ext.util.CSS.createStyleSheet(`
        .vertical-center-grid .x-grid-cell-inner {
            height: 130px !important;
            padding: 0 !important;
        }
        .vertical-center-grid .x-grid-row {
            height: 130px !important;
        }
    `);

        const data = [{
            'u_type': '交付质量',
            'u_score': '100',
            'u_desc': `1、交付产品未出现质量问题，且配合海信完成业主特定需求。100分。
2、交付产品未出现质量问题。80分。
3、交付产品出现质量问题，未造成影响，60分。
4、交付产品出现质量问题，对我司项目造成一定影响，例施工进度、客户满意度（未发函、罚款）造成实施影响，30分。
5、交付产品出现质量问题，对我司项目造成严重影响，例客户投诉函件、罚款单、批次质量问题、安全问题等，0分。`,
            'u_finalscore': finalScore
        },
        {
            'u_type': '服务响应',
            'u_score': '100',
            'u_desc': ``,
            'u_finalscore': finalScore
        }];
        pgrid.store.loadData(data);
        pwin.show();
    }

}

//确认
function OkBtn1(datePicker, window) {
    const selectedDate = datePicker.getValue();
    const formattedDate = Ext.Date.format(selectedDate, 'Y-m-d');
    const dgrid = Ext.getCmp('KcBillbodyList');
    if (!dgrid) {
        Ext.Msg.alert("提示", "请先显示明细！")
        window.close();
        return
    }
    const selectedRows = dgrid.getSelectionModel().getSelection();
    let cheakRrr = []
    // dgrid.getStore().each(item=>{
    //     cheakRrr.push(item.get("PhId"))
    // })
    selectedRows.forEach(row => {
        cheakRrr.push(row.get("PhId")); // 收集选中行的 PhId
    });
    if (cheakRrr.length == 0) {
        Ext.Msg.alert("提示", "请先显示明细！")
        window.close();
        return
    }
    console.log(`全部行PHID`, cheakRrr);
    try {
        execServer('updateTzsj', { phid: `(${cheakRrr.join(",")})`, date: formattedDate }, function (res) {
            if (res.status == "success") {
                Ext.Msg.alert("提示", "状态更新成功，请刷新页面查看");
            } else {
                Ext.Msg.alert("提示", "状态更失败，请刷新页面查看");
            }
        })
    } catch (er) {
        Ext.Msg.alert("提示", "请先显示明细！")
    }
    // toolbar.get("save").enable()
    // 关闭弹窗
    window.close();
}
function OkBtn2(datePicker, window) {
    const selectedDate = datePicker.getValue();
    const formattedDate = Ext.Date.format(selectedDate, 'Y-m-d');
    const dgrid = Ext.getCmp('KcBillbodyList');
    if (!dgrid) {
        Ext.Msg.alert("提示", "请先显示明细！")
        window.close();
        return
    }
    const selectedRows = dgrid.getSelectionModel().getSelection();
    const cheakRrr = []
    // dgrid.getStore().each(item=>{
    //     cheakRrr.push(item.get("PhId"))
    // })
    selectedRows.forEach(row => {
        cheakRrr.push(row.get("PhId")); // 收集选中行的 PhId
    });
    if (cheakRrr.length == 0) {
        Ext.Msg.alert("提示", "请先显示明细！")
        window.close();
        return
    }
    try {
        execServer('updateYsDate', { phid: `(${cheakRrr.join(",")})`, date: formattedDate }, function (res) {
            if (res.status == "success") {
                Ext.Msg.alert("提示", "状态更新成功，请刷新页面查看");
            } else {
                Ext.Msg.alert("提示", "状态更失败，请刷新页面查看");
            }
        })
    } catch (err) {
        Ext.Msg.alert("提示", "请先显示明细！")
    }
    // toolbar.get("save").enable()
    // 关闭弹窗
    window.close();
}
function createWindow(fun) {
    // 创建提示标签
    const label = Ext.create('Ext.form.Label', {
        text: '请选择要重置的时间',
        style: 'margin-bottom: 10px;'
    });

    // 创建日期选择器
    const datePicker = Ext.create('Ext.picker.Date', {
        format: 'Y-m-d', // 设置日期格式
        width: 220
    });

    // 创建确认按钮
    const okButton = Ext.create('Ext.button.Button', {
        text: '确定',
        handler: () => { fun(datePicker, window) }
    });

    // 创建取消按钮
    const cancelButton = Ext.create('Ext.button.Button', {
        text: '取消',
        handler: function () {
            // 关闭弹窗
            window.close();
        }
    });

    // 创建弹窗
    const window = Ext.create('Ext.window.Window', {
        title: '请选择日期',
        width: 300,
        height: 315,
        layout: 'fit', // 使用 vbox 布局，以便垂直排列组件
        items: [datePicker],
        buttons: [okButton, cancelButton],
        modal: true // 设置为模态窗口
    });
    return window;
}
function AllReady() {
    var mstform = Ext.getCmp("KC_INKCGRK_Head"); //获取容器
    var dgrid = Ext.getCmp("KC_INKCGRK_Body");
    var Toolbar = Ext.getCmp("toolbar");
    mstform.on("dataready", function () {
        console.log("Data ready event triggered");
        if (otype == "view") {
            console.log("view");
            Toolbar.get("save").disabled = false;
            dgrid.setReadOnlyCol("user_atdt", false);
        }

    });
    console.log('11111111111111111111111111111');
    mstform.getItem('user_is_evaluation').setValue("0");
    var dstore = dgrid.store;

    var PhidTrProj = mstform.queryById("PhidTrProj"); //项目工程
    var user_pc_no = mstform.queryById("user_pc_no")//项目编号
    var user_division = mstform.queryById("user_division"); //获取字段
    var user_product_line = mstform.queryById("user_product_line");

    var user_yhd_name = mstform.queryById("user_yhd_name");
    var user_yhd_no = mstform.queryById("user_yhd_no");
    var user_yhd_dt = mstform.queryById("user_yhd_dt");
    var user_yhd_amt = mstform.queryById("user_yhd_amt"); //要货单金额--不含税
    var PhidContractno = mstform.queryById("PhidContractno"); //合同编码
    var ContractName = mstform.queryById("ContractName");
    var user_cnt_amt = mstform.queryById("user_cnt_amt");
    var PhidCompno = mstform.queryById("PhidCompno");
    var user_regional_center = mstform.queryById("user_regional_center");
    var user_sl_organize = mstform.queryById("user_sl_organize"); //收料组织
    var PhidDeptno = mstform.queryById("PhidDeptno"); //收料部门
    var user_ck_no = mstform.queryById("user_ck_no");
    var PhidChkpsn = mstform.queryById("PhidChkpsn");
    var user_bill_type = mstform.queryById("user_bill_type");
    var PhidOcode = mstform.queryById("PhidOcode");
    var user_xsht_name = mstform.queryById("user_xsht_name");
    var user_xsht_no = mstform.queryById("user_xsht_no");
    var PhidWarehouse = mstform.queryById("PhidWarehouse"); //新增时根据方案自动生成不同的汇总层级

    // var phid_schemeid = mstform.getItem("phid_schemeid"); //方案ID

    // if (otype == "add") {
    // 	console.log(phid_schemeid.getValue(), "phid_schemeid.getValue()");

    // 	// if (phid_schemeid.getValue() == "747220909017002") {
    // 	// 	u_cj.setValue("2");
    // 	// 	BatchBindCombox([u_cj]);
    // 	// } else if (phid_schemeid.getValue() == "747220909023003") {
    // 	// 	u_cj.setValue("1");
    // 	// 	BatchBindCombox([u_cj]);
    // 	// }
    // }
    // if (otype == 'add') {
    //     setTimeout(() => {
    //         PhidOcode.setValue('')
    //         BatchBindCombox([PhidOcode]);
    //     }, 200);
    // }

    PhidTrProj.addListener("helpselected", function () {
        execServer(
            "getPtInfoByPhid",
            { phid: PhidTrProj.getValue() },
            function (res) {
                const obj = JSON.parse(res.data)[0].extendObjects;
                console.log(obj, "obj");
                user_division.setValue(obj.division_phid);
                PhidOcode.setValue(obj.org_phid);
                user_product_line.setValue(obj.midwife_phid);
                user_regional_center.setValue(obj.regional_center_phid);
                user_pc_no.setValue(obj.pc_no)
                BatchBindCombox([PhidOcode]);
                BatchBindCombox([user_division]);
                BatchBindCombox([user_product_line]);
                BatchBindCombox([user_regional_center]);
            }
        );
        execServer(
            "GETxs_cnt",
            { pc: PhidTrProj.getValue() },
            function (res) {
                const obj = JSON.parse(res.data)[0].extendObjects;
                console.log(obj, "obj");
                user_xsht_name.setValue(obj.phid);
                user_xsht_no.setValue(obj.bill_no);
                BatchBindCombox([user_xsht_name]);
            }
        );
    });
    PhidContractno.addListener("change", function () {
        let phid_customer_ent = ''
        console.log(PhidContractno.getValue(), "PhidContractno.getValue()");
        execServer(
            "getCntOrg",
            { phid: PhidContractno.getValue() },
            function (res) {
                if (res.count > 0) {
                    try {
                        var obj = JSON.parse(res.data)[0].extendObjects;
                        console.log(obj, "obj");
                        user_sl_organize.setValue(obj.phid_org);
                        PhidDeptno.setValue(obj.user_apply_dept);
                        BatchBindCombox([user_sl_organize]);
                        BatchBindCombox([PhidDeptno]);
                    } catch (error) { }
                }
            }
        );
        execServer("searchJfdwByCg", { phid: PhidContractno.getValue() }, (res) => {
            if (res.count == 0 || !res.count) {
                return;
            } else {
                const data = JSON.parse(res.data)[0].extendObjects
                console.log(data);
                console.log(data.phid_customer_ent);
                mstform.getItem('user_jz_org').setValue(data.fromorg_id)
                BatchBindCombox([mstform.getItem("user_jz_org")]);
                //  execServer("searchJzzz", { phid :`${data.phid_customer_ent}` }, (res) => {
                //     console.log(res);
                //     if (res.count == 0 || !res.count) {
                //       return;
                //     } else {
                //      const data = JSON.parse(res.data)[0].extendObjects
                //      mstform.getItem('user_jz_org').setValue(data.fromorg_id)
                //       BatchBindCombox([mstform.getItem("user_jz_org")]);
                //     }
                //   });
            }
        });


        // 获取合同信息
        getCntMInfoByPhid(mstform.queryById("PhidContractno").getValue())
    });
    dstore.on("datachanged", async function (dstore, eOpts) {
        console.log(`数据发生变化`);
        const records = dstore.getRange();
        for (const record of records) {
            try {
                console.log(record.data.user_storage_type);

                if (!record.data.user_storage_type) {
                    //如果为空，则默认为合格默认
                    record.set("user_storage_type", "RKLX0001");
                }
                // record.set("user_if_kxys", 0);

                record.set("user_yfd_rest_qty", record.data.Qty);

                dgrid.getView().refresh()
            } catch (error) {
                console.error(error);
            }
        }
    });
    user_bill_type.addListener("change", function () {
        console.log(user_bill_type.getValue(), "PhidContractno.getValue()");
        if (user_bill_type.getValue() == 'RKLX0004') {
            mstform.getItem('PhidContractno').userSetMustInput(false);
            mstform.getItem('PhidCompno').userSetMustInput(false);
        } else {
            mstform.getItem('PhidContractno').userSetMustInput(true);
            mstform.getItem('PhidCompno').userSetMustInput(true);
        }
    });
    PhidContractno.on("beforetriggerclick", function (eOp, ignoreBeforeEvent) {
        //选择合同之前先选择项目名称
        if (PhidTrProj.getValue()) {
            // user_yhd_name.setOutFilter({ phid_pc: PhidTrProj.getValue() });
        } else {
            Ext.Msg.alert("提示", "请先选择项目工程");
            mstform.getItem("PhidTrProj").focus();
            return false;
        }
    });
    //要货单根据合同过滤

    user_yhd_name.on("beforetriggerclick", function (eOp, ignoreBeforeEvent) {
        console.log(PhidContractno.getValue());

        if (PhidContractno.getValue()) {
            user_yhd_name.setOutFilter({ phid_contract: PhidContractno.getValue() });
        } else {
            Ext.Msg.alert("提示", "请先选择合同");
            mstform.getItem("PhidContractno").focus();
            return false;
        }
    });
    user_yhd_name.addListener("helpselected", function () {
        execServer(
            "getOrderInfo",
            { yhd: user_yhd_name.getValue() },
            function (res) {
                if (res.count > 0) {
                    var obj = JSON.parse(res.data);
                    user_yhd_no.setValue(obj[0].extendObjects.no);
                    user_yhd_dt.setValue(obj[0].extendObjects.dt);
                    user_yhd_amt.setValue(obj[0].extendObjects.yhd_amt);
                    PhidContractno.setValue(obj[0].extendObjects.phid);
                    ContractName.setValue(obj[0].extendObjects.cnt_name);
                    user_cnt_amt.setValue(obj[0].extendObjects.cnt_amt);
                    PhidCompno.setValue(obj[0].extendObjects.gys);
                    BatchBindCombox([PhidContractno]);
                    BatchBindCombox([PhidCompno]);

                    console.log(PhidContractno, "PhidContractno");
                }
            }
        );
    });

    /*var user_yhd_name = mstform.getItem('user_yhd_name');
    user_yhd_name.on('beforetriggerclick', function (eOp, ignoreBeforeEvent) {
user_yhd_name.setOutFilter({ phid_pc: PhidTrProj.getValue() })
});*/

    PhidWarehouse.addListener("helpselected", function () {
        execServer(
            "getStoreInfo",
            { store: PhidWarehouse.getValue() },
            function (res) {
                if (res.count > 0) {
                    var obj = JSON.parse(res.data);
                    user_ck_no.setValue(obj[0].extendObjects.no);
                    PhidChkpsn.setValue(obj[0].extendObjects.manapsn)
                    BatchBindCombox([PhidChkpsn])
                }
            }
        );
    });

    if (otype == "add") {
        dstore.on("datachanged", function (store, records, index, eOpts) {
            SetTotal();
        });
        dstore.on("add", function (store, records, index, eOpts) {
            SetTotal();
        });
        dstore.on("remove", function (store, records, index, eOpts) {
            SetTotal();
        });
    }
    dgrid.addListener("edit", function (editor, e) {
        var record = e.record;
        if (e.originalValue == e.value) {
            return;
        }
        record.set("user_fpsyje", record.data.TaxMony)
        // record.set("user_yfd_rest_qty", record.data.Qty);
        record.set("user_thsyl", record.data.Qty);

        // record.set("u_fpje");
        SetTotal();
    });

    function SetTotal() {
        let sum_amt = 0;
        dstore.each(function (item) {
            console.log("shcuhujine" + item.get("TaxMony"));
            sum_amt += item.get("TaxMony");
        });
        mstform.getItem("user_rk_amt").setValue(sum_amt);
        dgrid.getView().refresh()
    }

    function getCntMInfoByPhid(phid) {
        if (!phid) return
        const user_sup_con_person = mstform.queryById("user_sup_con_person")
        execServer("getCntMInfoByPhid", { phid }, (res) => {

            if (res.count == 0) return
            const _data = JSON.parse(res.data)[0].extendObjects
            console.log(`合同信息`, _data);
            user_sup_con_person.setValue(_data.gflxr_name)
        })
    }


}
function beforeSaveEdit() {
    var mstform = Ext.getCmp("KC_INKCGRK_Head");
    var dgrid = Ext.getCmp("KC_INKCGRK_Body");
    var dstore = dgrid.store;

    var user_is_evaluation = mstform.getItem('user_is_evaluation').getValue();
    if (user_is_evaluation == "0" || user_is_evaluation == null) {
        var arr = [];
        Ext.Array.each(dstore.data.items, function (record) {
            arr.push(record.get('user_end_time'));
        });
        var maxDate = new Date(Math.max.apply(null, arr.map(time => new Date(time).getTime())));
        var currentDate = new Date();
        var daysDiff = Math.floor((maxDate.getTime() - currentDate.getTime()) / (1000 * 60 * 60 * 24));
        var initialScore = 80;
        var finalScore = initialScore;
        execServer("u_jfjsx", {}, (res) => {
            if (res.count == 0) return;
            const _data = JSON.parse(res.data)[0].extendObjects;
            var u1 = parseInt(_data.c_name);    // 每多少天扣一次
            var u2 = parseInt(_data.c_descript); // 每次扣多少分
            // 仅当天数差为正数时才扣分
            if (daysDiff > 0) {
                var deduction = Math.floor(daysDiff / u1) * u2;
                finalScore = Math.max(0, initialScore - deduction); // 确保不低于0分
            }
            console.log(`天数差: ${daysDiff}天`);
            console.log(`扣分规则: 每${u1}天扣${u2}分`);
            console.log(`最终得分: ${finalScore}分`);
        });
        Evaluation(mstform, finalScore)
        return false
    } else {
        return true;
    }
    function Evaluation(mstform, finalScore) {
        const fields = [
            { name: 'u_type' },
            { name: 'u_score' },
            { name: 'u_desc' },
            { name: 'u_finalscore' }
        ];
        var store = Ext.create('Ext.data.Store', {
            autoDestroy: true,
            proxy: {
                type: 'memory'
            },
            data: [],
            sorters: [{
                property: 'start',
                direction: 'ASC'
            }],
            fields: fields,
        });

        const column = [
            {
                text: '序号',
                width: 60,
                align: 'center',
                renderer: function (value, metaData, record, rowIndex) {
                    metaData.style = "text-align:center;display:flex;align-items:center;justify-content:center;height:180px";
                    return rowIndex + 1;
                },
                sortable: false,
                menuDisabled: true
            },
            {
                text: '二级分类',
                dataIndex: 'u_type',
                width: 80,
                align: 'center',
                sortable: false,
                renderer: function (value, meta) {
                    meta.style = "text-align:center;display:flex;align-items:center;justify-content:center;height:180px";
                    return value;
                },
                menuDisabled: true
            },
            {
                text: '分值',
                dataIndex: 'u_score',
                width: 40,
                align: 'center',
                sortable: false,
                renderer: function (value, meta) {
                    meta.style = "text-align:center;display:flex;align-items:center;justify-content:center;height:180px";
                    return value;
                },
                menuDisabled: true
            },
            {
                text: '标准调整',
                dataIndex: 'u_desc',
                width: 750,
                align: 'center',
                sortable: false,
                renderer: function (val, meta) {
                    meta.style = "white-space:pre-wrap;word-wrap:break-word;padding:5px;text-align:left;height:180px";
                    return val;
                },
                cellWrap: true,
                menuDisabled: true
            },
            {
                text: '得分',
                dataIndex: 'u_finalscore',
                width: 40,
                align: 'center',
                renderer: function (value, meta) {
                    meta.style = "text-align:center;display:flex;align-items:center;justify-content:center;height:180px";
                    return value;
                },
                editor: {
                    xtype: 'textfield',
                    allowBlank: false
                }
            }
        ];
        const rowHeight = 120;
        const gridHeight = rowHeight + 30;
        const windowHeight = gridHeight + 100;

        var pgrid = new Ext.grid.GridPanel({
            height: gridHeight,
            width: 1000,
            autoScroll: false,
            cls: 'vertical-center-grid',
            store: store,
            columns: column,
            viewConfig: {
                preserveScrollOnRefresh: true,
                getRowClass: function () {
                    return 'fixed-height-row';
                }
            },
            plugins: [
                Ext.create('Ext.grid.plugin.CellEditing', {
                    clicksToEdit: 1,
                    autoCancel: false
                })
            ]
        });

        var pwin = new Ext.Window({
            title: '供应商评价',
            layout: 'fit',
            width: 1000,
            height: windowHeight,
            closable: false,
            closeAction: 'hide',
            items: [pgrid],
            header: {
                titleAlign: 'center'
            },
            buttons: [{
                text: '确定',
                handler: function () {
                    var newData = store.data.items;
                    if (newData.length > 0) {
                        mstform.getItem('user_score1').setValue(newData[0].data.u_finalscore);
                    }
                    mstform.getItem('user_is_evaluation').setValue("1");
                    this.up("window").close();
                }
            }, {
                text: '返回',
                handler: function () {
                    this.up("window").close();
                }
            }],
        });
        Ext.util.CSS.createStyleSheet(`
        .vertical-center-grid .x-grid-cell-inner {
            height: 130px !important;
            padding: 0 !important;
        }
        .vertical-center-grid .x-grid-row {
            height: 130px !important;
        }
    `);

        const data = [{
            'u_type': '交付及时性',
            'u_score': '100',
            'u_desc': `1、支撑项目紧急需求，优于品类/合同约定交付时间，进行交付，100分。
2、按照品类/合同约定交付时间到货，进行交付。80分。
3、未按照品类/合同约定交付时间到货，未造成影响，60分。
4、未按照品类/合同约定交付时间到货，对我司项目造成一定影响，例施工进度、客户满意度（未发函、罚款）造成实施影响，30分。
5、未按照品类/合同约定交付时间到货，对我司项目造成严重影响，例客户投诉函件、罚款单、批次质量问题、安全问题等，0分。`,
            'u_finalscore': finalScore
        }];
        pgrid.store.loadData(data);
        pwin.show();
    }
}

